package com.sky.checkutil.util;


import com.sky.checkutil.domain.CheckParam;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具
 *
 * @author: hjy
 * @create: 2023-12-28 13:19
 **/
public class FileUtil {

    /**
     * 获取文件夹下的所有文件路径
     *
     * @param checkParam
     * @return
     */
    public static List<String> getJavaFilePaths(CheckParam checkParam) {
        List<String> javaFilePaths = new ArrayList<>();
        File folder = new File(checkParam.folderPath);
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            for (File file : files) {
                if (checkFileSuffixRule(file, checkParam.getCheckFileSuffix())) {
                    javaFilePaths.add(file.getAbsolutePath());
                } else if (checkParam.checkBelowFolder && checkFolderNameRule(file, checkParam.excludeFolder)) {
                    //递归检测文件夹
                    checkParam.setFolderPath(file.getAbsolutePath());
                    javaFilePaths.addAll(getJavaFilePaths(checkParam));
                }
            }
        }
        return javaFilePaths;
    }

    /**
     * 判断满足文件夹名称校验规则
     *
     * @param file
     * @param excludeFolder
     * @return
     */
    private static Boolean checkFolderNameRule(File file, List<String> excludeFolder) {
        if (file != null && file.isDirectory()) {
            if (excludeFolder == null) return true;
            if (!excludeFolder.contains(file.getName())) return true;
        }
        return false;
    }

    /**
     * 判断满足文件后缀名校验规则
     *
     * @param file
     * @param fileSuffix
     * @return
     */
    private static Boolean checkFileSuffixRule(File file, List<String> fileSuffix) {
        if (file != null && file.isFile()) {
            if (fileSuffix == null) return true;
            for (String suffix : fileSuffix) {
                if (file.getName().endsWith(suffix)) return true;
            }
        }
        return false;
    }


}
